﻿using System;
using System.Timers;

namespace ListViewSample
{
    sealed class Presenter
    {
        // ********************************************** //
        #region [ member fields ]

        private readonly IView m_view;
        private readonly Timer m_timer;
        private readonly string[] m_names;
        private readonly Random m_random;
        private volatile int m_counter;
        private int m_maxNum;

        #endregion

        // ********************************************** //
        #region [ constructor ]

        public Presenter(IView view)
        {
            m_view = view;

            m_timer = new Timer(1000);
            m_timer.Elapsed += this.OnElapsed;

            m_names = new string[]
                          {
                              "stasi",
                              "kgb",
                              "cia",
                              "nkvd",
                              "mi5"
                          };
            m_random = new Random();

            m_counter = 0;
            m_maxNum = 30;
        }

        #endregion

        // ********************************************** //
        #region [ destructor ]

        private bool m_disposed;

        ~Presenter()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (m_disposed)
                return;

            try
            {
                if (disposing)
                {
                    m_timer.Elapsed -= this.OnElapsed;
                    m_timer.Stop();
                    m_timer.Close();
                }
            }
            finally
            {
                m_disposed = true;
            }
        }

        #endregion

        // ********************************************** //
        #region [ public APIs ]

        public void Start()
        {
            m_timer.Start();
        }

        public int MaxNum
        {
            get { return m_maxNum; }
            set { m_maxNum = value; }
        }

        #endregion

        // ********************************************** //
        #region [ private helpers ]

        private void OnElapsed(object sender, ElapsedEventArgs evtargs)
        {
            ++m_counter;

            if (m_counter > m_maxNum)
            {
                m_view.Clear();
                m_counter = 0;
            }
            else
            {
                int id = m_random.Next(1, 100);
                float value = (float)m_random.NextDouble();
                string name = m_names[id % m_names.Length];

                m_view.AddNewMessage(name, id, value);
            }
        }

        #endregion
    }
}
